import os
from fastapi import APIRouter, UploadFile, File, Request
from models.ai.utils.common import R, saveRequestFile, saveRequestFileByByte
from models.ai.services import SpeechToTextService
from models.ai.config.settings import UPLOAD_PATH, MODEL_PATH
from modelscope import snapshot_download

router = APIRouter(prefix="/ai/speechToText")

@router.post("/convert")
async def convert(audio: UploadFile = File(...)):
    filePath = await saveRequestFile(audio, distPath=UPLOAD_PATH)
    service = SpeechToTextService()
    text = service.convert(filePath)
    os.remove(filePath)
    return R.data(text)

@router.post("/convertByByte")
async def convertByByte(request: Request):
    # 读取请求体中的字节数据
    audio_bytes = await request.body()
    filePath = await saveRequestFileByByte(audio_bytes, distPath=UPLOAD_PATH)
    service = SpeechToTextService()
    text = service.convert(filePath)
    os.remove(filePath)
    return R.data(text)

@router.get("/downloadModel")
async def downloadModel():
    model_list = [
        "iic/speech_paraformer-large-vad-punc_asr_nat-zh-cn-16k-common-vocab8404-pytorch",
        "iic/speech_fsmn_vad_zh-cn-16k-common-pytorch",
        "iic/punc_ct-transformer_zh-cn-common-vocab272727-pytorch",
    ]
    for model_name in model_list:
        snapshot_download(model_name, cache_dir=MODEL_PATH)
    return R.success()
